import { STORAGE_KEYS } from "@/config";
import router from "@/router";
import { useUserStore } from "@/stores/useUserStore";
import axios, {
  type AxiosInstance,
  type AxiosRequestConfig,
  type AxiosResponse,
} from "axios";
import { ElMessage } from "element-plus";

// 创建axios实例
const instance: AxiosInstance = axios.create({
  baseURL: import.meta.env.VITE_API_BASE_URL, // 基础URL  
  timeout: 10000, // 请求超时时间
  headers: {
    "Content-Type": "application/json", // 请求头
  },
});

// 请求拦截器
instance.interceptors.request.use(
  (config) => {
    // 获取token
    const token = useUserStore().token;
    // 如果有token则添加到请求头
    if (token && config.headers) {
      config.headers.Authorization = `Bearer ${token}`;
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

// 响应拦截器
instance.interceptors.response.use(
  (response: AxiosResponse) => {
    const res = response.data;
    // console.log('响应拦截器：', res)
    // 如果返回的状态码不是200，说明接口有问题，应该提示错误信息
    if (res.code !== 200) {
      ElMessage.error(res.message || "系统错误");

      // 如果是认证相关错误，清除token并跳转到登录页
      if (res.code === 401) {
        localStorage.removeItem(STORAGE_KEYS.TOKEN);
        router.push("/login");
      }

      return Promise.reject(new Error(res.message || "系统错误"));
    }
    return res;
  },
  (error) => {
    console.error("请求错误", error);
    ElMessage.error(error.message || "网络错误");
    return Promise.reject(error);
  }
);

// 封装GET请求
export const get = <T>(
  url: string,
  params?: any,
  config?: AxiosRequestConfig
): Promise<T> => {
  return instance.get(url, { params, ...config });
};

// 封装POST请求
export const post = <T>(
  url: string,
  data?: any,
  config?: AxiosRequestConfig
): Promise<T> => {
  return instance.post(url, data, config);
};

// 封装PUT请求
export const put = <T>(
  url: string,
  data?: any,
  config?: AxiosRequestConfig
): Promise<T> => {
  return instance.put(url, data, config);
};

// 封装DELETE请求
export const del = <T>(
  url: string,
  config?: AxiosRequestConfig
): Promise<T> => {
  return instance.delete(url, config);
};

export default instance;
